<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------
use think\Db;
// 应用公共文件

/**
 *获取供应链中返利商品计算价格比例
 * @param $id  int 供应链中商品id
 * @param $type int 1表示返利商城2表示爆品
 * @return 比例
 */
function getReturnPop($id,$type)
{
    $data = Db::name("choice_goods")
        ->field("return_proportion,hot_proportion")
        ->where(['goods_id'=>$id])
        ->find();
    if($type == 1)
    {
        return $data['return_proportion'] / 100;
    }else{
        return $data['hot_proportion'] / 100;
    }

}
/**
 * 驼峰命名转下划线命名
 * @param $str
 * @return string
 */
function toUnderScore($str)
{
    $dstr = preg_replace_callback('/([A-Z]+)/', function ($matchs) {
        return '_' . strtolower($matchs[0]);
    }, $str);
    return trim(preg_replace('/_{2,}/', '_', $dstr), '_');
}
/**
 * 求两个已知经纬度之间的距离,单位为米
 *
 * @param lng1 $ ,lng2 经度
 * @param lat1 $ ,lat2 纬度
 * @return float 距离，单位米
 * @author www.Alixixi.com
 */
function get_distance($lng1, $lat1, $lng2, $lat2) {
    // 将角度转为狐度
    $radLat1 = deg2rad($lat1); //deg2rad()函数将角度转换为弧度
    $radLat2 = deg2rad($lat2);
    $radLng1 = deg2rad($lng1);
    $radLng2 = deg2rad($lng2);
    $a = $radLat1 - $radLat2;
    $b = $radLng1 - $radLng2;
    $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137 * 1000;
    return $s;
}

/**
 *直接根据header头参数获取用户id
 * @parama
 */
function get_header_id($key){
    return get_user_id(get_header_param($key));
}
//通过token获取用户id
function get_user_id($key)
{
    return strstr( $key,"_",true );
}
//获取header头中参数
function get_header_param($key)
{
    return request()::instance()->header($key);
}
//写日志文件
function writeLog($content,$fileName)
{
    $myfile = fopen ( ROOT_PATH."public".DS.$fileName, "a+" );
    fwrite($myfile, $content.date("Y-m-d H:i:s").PHP_EOL);
    fclose($myfile);
}
//返回数据
function returnJson($code,$msg="success",$data=null)
{
    if($data == null)
    {
        $data =  [];
    }
    echo json_encode(['code'=>$code,'msg'=>$msg,'data'=>$data]);die;
}
#数组转对象
function array_to_object($arr)
{
    if (gettype($arr) != 'array') {
        return;
    }
    foreach ($arr as $k => $v) {
        if (gettype($v) == 'array' || getType($v) == 'object') {
            $arr[$k] = (object)array_to_object($v);
        }
    }
    return (object)$arr;
}
/**
 * type str 为GET或者POST
 * post传参调用为:  curlHttp($url,'POST',json_encode(input()))
 * get传参调用为:   curlHttp($url,'GET');
 *
 */
function curlHttp( $url,$type='GET', $data='')
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); //// https请求 不验证证书和hosts
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
    if( $type == 'GET')
    {
        curl_setopt($curl, CURLOPT_HEADER, FALSE);  //不返回报文头部
    }else
    {
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json;charset=utf-8'));
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    $output = curl_exec($curl);
    curl_close($curl);
    return json_decode($output,TRUE);
}

/**
 * [生成订单号]
 * @param $order_type  [1=商品  2=售后]
 * @param int $form
 * @param $user_id  [用户id]
 * @return string
 */
function get_order1($order_type, $form = 1, $user_id)
{
    $user_id = sprintf('%04s', $user_id);
    $user_id = substr($user_id, -4);
    $host_id = config('database.host_id');
    $host_id = sprintf('%02s', $host_id);
    $host_id = substr($host_id, -2);
    return $order_type . $form . $user_id . $host_id . date('md') . randCode(8, 1);
}

/**
 * [生成随机字符串]
 * @param  integer $length [生成的长度]
 * @param  integer $type [生成的类型]
 * @return [type]   str       [description]
 * @php 随机码类型：0，数字+大写字母；1，数字；2，小写字母；3，大写字母；4，特殊字符；-1，数字+大小写字母+特殊字符
 */
function randCode($length = 5, $type = 0)
{
    $arr = array(1 => "0123456789", 2 => "abcdefghijklmnopqrstuvwxyz", 3 => "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 4 => "~@#$%^&*(){}[]|");
    if ($type == 0) {
        array_pop($arr);
        $string = implode("", $arr);
    } else if ($type == "-1") {
        $string = implode("", $arr);
    } else {
        $string = $arr[$type];
    }
    $count = strlen($string) - 1;
    $code = "";
    for ($i = 0; $i < $length; $i++) {
        $str[$i] = $string[rand(0, $count)];
        $code .= $str[$i];
    }
    return $code;
}

/**
 * CMF密码加密方法
 * @param string $pw       要加密的原始密码
 * @param string $authCode 加密字符串
 * @return string
 */
function cmf_password($pw, $authCode = '')
{
    if (empty($authCode)) {
        $authCode = 'Dex9gPtaHut5nzobzV';
    }
    $result = "###" . md5(md5($authCode . $pw));
    return $result;
}

/**
 * CMF密码加密方法 (X2.0.0以前的方法)
 * @param string $pw 要加密的原始密码
 * @return string
 */
function cmf_password_old($pw)
{
    $decor = md5('cmf_');
    $mi    = md5($pw);
    return substr($decor, 0, 12) . $mi . substr($decor, -4, 4);
}

/**
 * CMF密码比较方法,所有涉及密码比较的地方都用这个方法
 * @param string $password     要比较的密码
 * @param string $passwordInDb 数据库保存的已经加密过的密码
 * @return boolean 密码相同，返回true
 */
function cmf_compare_password($password, $passwordInDb)
{
    if (strpos($passwordInDb, "###") === 0) {
        return cmf_password($password) == $passwordInDb;
    } else {
        return cmf_password_old($password) == $passwordInDb;
    }
}

/**
 * 获取客户端IP地址
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @param boolean $adv  是否进行高级模式获取（有可能被伪装）
 * @return string
 */
function get_client_ip($type = 0, $adv = true)
{
    return request()->ip($type, $adv);
}






